#include "imagereceiver.h"
#include <QDebug>
ImageReceiver::ImageReceiver()
{

}

ImageReceiver::ImageReceiver(quint16 port)
    : udpSocket(new QUdpSocket(this)), totalBytes(0), receivedBytes(0)
{
    udpSocket->bind(QHostAddress::Any, port);
    connect(udpSocket, &QUdpSocket::readyRead, this, &ImageReceiver::processPendingDatagrams);
    reciveFlag =0;
}

void ImageReceiver::processPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        datagram.resize(udpSocket->pendingDatagramSize());
        udpSocket->readDatagram(datagram.data(), datagram.size());

        switch (reciveFlag) {
        case 0:  // 分析图像包头
            if(datagram.size() == 6)
            {
                if(datagram[0] == 0xaa && datagram[1] == 0x55)
                {
                    reciveFlag = 1;
                    QDataStream sizeStream(datagram.mid(2));
                    sizeStream >> totalBytes;
                    qDebug()<<"收到1帧图像, 图像大小:"<<totalBytes;
                    buffer.reserve(totalBytes);
                    receivedBytes = 0;
                }
            }
            break;
        case 1:
            receivedBytes += datagram.size();
            buffer.append(datagram);
            // 检查是否接收完整个图像
            if (receivedBytes >= totalBytes)
            {
                QImage image;
                image.loadFromData(buffer, "PNG");
                if (!image.isNull())
                {
                    // 显示接收到的图像
                    //imageLabel->setPixmap(QPixmap::fromImage(image));
                }
                // 重置缓冲区和计数器以接收下一个图像
                buffer.clear();
                totalBytes = 0;
                receivedBytes = 0;
                reciveFlag =0;
            }
            break;
        default:
            break;
        }
    }
}
